package com.edol.painting.data;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;

import com.doodle.common.drawable.MeasuredAsyncDrawable;
import com.doodle.common.utils.AsyncDataLoader;
import com.doodle.common.utils.BitmapUtils;
import com.edol.painting.data.PaintingDatabase.PaintingEntry;
import com.edol.painting.utils.Constant;

public class PaintingEntryLoader extends AsyncDataLoader<PaintingEntry> {
	
	private final long mId;
	private final Bitmap mPaintingBrush;

	public PaintingEntryLoader(Context context, long id, Bitmap paintingBrush) {
		super(context);
		mId = id;
		mPaintingBrush = paintingBrush;
	}

	@Override
	public PaintingDatabase.PaintingEntry loadInBackground() {
		PaintingDatabase.PaintingEntry painting = null;
		
		int width = Constant.PAINTING_WIDTH;
		int height = Constant.PAINTING_HEIGHT;
		
		if (mId >= 0) {
			painting = PaintingDatabase.getInstance().getPaintingById(mId);
            if (painting == null) return null;
			if (mPaintingBrush != null && mPaintingBrush.getWidth() == width && mPaintingBrush.getHeight() == height) {
				if (mPaintingBrush.isMutable()) {
					painting.mPaintingBrush = mPaintingBrush;
				} else {
					painting.mPaintingBrush = mPaintingBrush.copy(mPaintingBrush.getConfig(), true);
				}
			} else {
				PaintingDatabase.getInstance().waitForSavingDone(painting.mId);
				try {
					painting.mPaintingBrush = BitmapUtils.loadBitmapFromFile(painting.mDirectory, width, height,
							BitmapUtils.FIT_LENGTH_LARGGER, MeasuredAsyncDrawable.DRAWABLE_TYPE_IMAGE, 0);
			    } catch (OutOfMemoryError e) {
			    	System.gc();
			    	painting.mPaintingBrush = BitmapUtils.loadBitmapFromFile(painting.mDirectory, width, height,
			        		BitmapUtils.FIT_LENGTH_LARGGER, MeasuredAsyncDrawable.DRAWABLE_TYPE_IMAGE, 0);
			    }
			}
		} else {
			painting = new PaintingDatabase.PaintingEntry();
			painting.mTheme = Color.WHITE;
		}
		return painting;
	}

}
